// 分别计算多个数组的结果，每个数组分组计算
package main

import (
	"fmt"
	"sync"
	"time"
)

var (
	arr1     []int = []int{52, 35, 43, 25, 35}
	arr2     []int = []int{23, 235, 234, 234, 235, 234, 123, 432}
	arr3     []int = []int{245, 3524, 35436, 234, 53}
	sum1     int
	sum2     int
	sum3     int
	chanarr  []chan int    = []chan int{make(chan int, 3), make(chan int, 3), make(chan int, 3)}
	doneChan chan struct{} = make(chan struct{})
	wait     sync.WaitGroup
)

func sumPartial(nList []int, no int) {
	defer wait.Done()
	var r int
	for _, i := range nList {
		r += i
	}
	chanarr[no] <- r
	fmt.Println("r:", r)
}

func sumArr(arr []int, no int) {
	for i := 0; i < len(arr); i += 5 {
		wait.Add(1)
		if i+5 > len(arr) {
			go sumPartial(arr[i:len(arr)], no)
		} else {
			go sumPartial(arr[i:i+5], no)
		}
	}
}

func commonSum(nList []int) int {
	var r int
	for _, v := range nList {
		r += v
	}
	return r
}

func main() {
	s := time.Now()
	go sumArr(arr1, 0)
	go sumArr(arr2, 1)
	go sumArr(arr3, 2)
	go func() {
		for _, v := range chanarr {
			defer close(v)
		}
		defer close(doneChan)
		wait.Wait()
	}()
	//通常将消费任务写成一个函数，方便直接return
	event := func() {
		for {
			select {
			case n0 := <-chanarr[0]:
				sum1 += n0
			case n1 := <-chanarr[1]:
				sum2 += n1
			case n2 := <-chanarr[2]:
				sum3 += n2
			case <-doneChan:
				return
			}
		}
	}
	event()

	fmt.Printf("sum1:%d,sum2:%d,sum3:%d\n", sum1, sum2, sum3)
	fmt.Printf("goroutine cost time:%s\n", time.Now().Sub(s))

	s = time.Now()
	fmt.Printf("sum1:%d,sum2:%d,sum3:%d\n", commonSum(arr1), commonSum(arr2), commonSum(arr3))
	fmt.Printf("commonsum cost time:%s\n", time.Now().Sub(s))
}
